<template>
  <div class="upcoming-list">
    <a-page-header
      title="活动预告管理"
      sub-title="管理首页活动预告，包括新增、编辑和删除等操作。"
    />
    <a-divider />
    <a-card class="search-card">
      <template #title>
        <span>搜索条件</span>
        <a-divider type="vertical" />
      </template>
      <a-form layout="inline">
        <a-form-item label="推荐标题">
          <a-input v-model:value="searchForm.title" placeholder="请输入推荐标题" allowClear />
        </a-form-item>
      
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>查询
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><reload-outlined /></template>重置
            </a-button>
            <a-button type="primary" @click="handleAdd" v-permission="'homepage:upcoming:add'">
              <template #icon><plus-outlined /></template>新增活动
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-table 
        bordered
        :columns="columns" 
        :data-source="tableData" 
        :loading="loading" 
        :pagination="{
            current: currentPage,
            pageSize: pageSize,
            total: total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`
        }"
        @change="handleTableChange"
        rowKey="id">
        <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
            <a-space>
                <a-button type="primary" @click="handleEdit(record)" v-permission="'homepage:upcoming:edit'">
                  <template #icon><edit-outlined /></template>编辑
                </a-button>
                <a-popconfirm
                title="确定要删除该活动预告吗？"
                @confirm="handleDelete(record.id)"
                ok-text="确定"
                cancel-text="取消"
                >
                <a-button type="primary" danger v-permission="'homepage:upcoming:delete'">
                  <template #icon><delete-outlined /></template>删除
                </a-button>
                </a-popconfirm>
            </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'image'">
              <img v-if="record.imageUrl" :src="`/api${record.imageUrl}`" alt="活动图片" style="width: 120px; height: 60px; object-fit: cover; border-radius: 4px;" />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'time'">
              <span>{{ record.startTime }} 至 {{ record.endTime }}</span>
            </template>
        </template>
    </a-table>

    <!-- 新增/编辑活动预告弹窗 -->
    <a-modal
      :title="dialogTitle"
      :visible="dialogVisible"
      @ok="submitForm"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
      width="700px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="活动标题" name="title">
          <a-input v-model:value="form.title" placeholder="请输入活动标题" />
        </a-form-item>
        <a-form-item label="活动图片" name="imageUrl">
          <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="/api/upload"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl.startsWith('data:') ? imageUrl : `/api${imageUrl}`" alt="活动图片" style="width: 100%; height: 100%; border-radius: 8px; object-fit: cover" />
            <div v-else>
              <loading-outlined v-if="imageLoading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="活动时间" name="timeRange">
          <a-range-picker 
            v-model:value="timeRange" 
            show-time 
            format="YYYY-MM-DD HH:mm:ss" 
            :placeholder="['开始时间', '结束时间']"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="活动ID" name="activityId">
          <a-input-group compact>
            <a-input-number 
              v-model:value="form.activityId" 
              :min="1" 
              style="width: calc(100% - 90px)" 
              placeholder="请选择活动ID" 
              readonly 
              disabled
            />
            <a-button type="primary" @click="openActivitySelector" style="width: 90px">选择活动</a-button>
          </a-input-group>
        </a-form-item>
        <a-form-item label="活动描述" name="description">
          <a-textarea v-model:value="form.description" placeholder="请输入活动描述" :rows="4" />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input-number v-model:value="form.sort" :min="0" style="width: 100%" />
        </a-form-item>

      </a-form>
    </a-modal>
    
    <!-- 活动选择弹窗 -->
    <a-modal
      title="选择活动"
      :visible="activitySelectorVisible"
      @cancel="handleActivitySelectorCancel"
      :footer="null"
      width="800px"
    >
      <div class="activity-selector">
        <div class="search-bar">
          <a-input
            v-model:value="activitySearchKeyword"
            placeholder="请输入活动名称"
            style="width: 250px; margin-right: 8px"
            @pressEnter="searchActivities"
          />
          <a-button type="primary" @click="searchActivities">
            <template #icon><search-outlined /></template>搜索
          </a-button>
        </div>
        
        <a-table
          :columns="activityColumns"
          :data-source="activityList"
          :loading="activityLoading"
          :pagination="activityPagination"
          @change="handleActivityTableChange"
          rowKey="id"
          bordered
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'cover'">
              <img v-if="record.coverImage" :src="`/api${record.coverImage}`" alt="活动封面" style="width: 60px; height: 30px; object-fit: cover; border-radius: 4px;" />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getActivityStatusColor(record.status)">
                {{ getActivityStatusText(record.status) }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button type="primary" size="small" @click="selectActivity(record)">
                选择
              </a-button>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed, watch } from 'vue';
import { message, PageHeader } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'UpcomingList',
  components: {
    SearchOutlined,
    ReloadOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    LoadingOutlined,
    APageHeader: PageHeader,
  },
  setup() {
    const formRef = ref(null);
    const loading = ref(false);
    const tableData = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const dialogVisible = ref(false);
    const dialogTitle = ref('新增活动预告');
    const isEdit = ref(false);
    const modalLoading = ref(false);
    const imageUrl = ref('');
    const imageLoading = ref(false);
    const fileList = ref([]);
    const timeRange = ref([]);
    
    // 活动选择器相关变量
    const activitySelectorVisible = ref(false);
    const activityList = ref([]);
    const activityLoading = ref(false);
    const activitySearchKeyword = ref('');
    const activityPagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    
    // 活动列表表格列定义
    const activityColumns = [
      {
        title: '活动ID',
        dataIndex: 'id',
        key: 'id',
        width: 80,
      },
      {
        title: '封面',
        dataIndex: 'coverImage',
        key: 'cover',
        width: 80,
      },
      {
        title: '活动名称',
        dataIndex: 'name',
        key: 'name',
        ellipsis: true,
      },
      {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right',
      },
    ];
    
    const searchForm = reactive({
      title: '',
      status: undefined,
    });
    
    const form = reactive({
      id: '',
      title: '',
      imageUrl: '',
      startTime: '',
      endTime: '',
      activityId: undefined, // 修改为与后端实体字段名一致
      description: '',
      sort: 0,
      status: 0,
    });
    
    // 监听时间范围变化，更新表单中的开始时间和结束时间
    watch(timeRange, (newVal) => {
      if (newVal && newVal.length === 2) {
        form.startTime = dayjs(newVal[0]).format('YYYY-MM-DD HH:mm:ss');
        form.endTime = dayjs(newVal[1]).format('YYYY-MM-DD HH:mm:ss');
      } else {
        form.startTime = '';
        form.endTime = '';
      }
    });
    
    const rules = {
      title: [
        { required: true, message: '请输入活动标题', trigger: 'blur' },
        { max: 50, message: '标题长度不能超过50个字符', trigger: 'blur' },
      ],
      imageUrl: [
        { required: true, message: '请上传活动图片', trigger: 'change' },
      ],
      activityId: [
        { required: true, message: '请输入活动ID', trigger: 'blur' },
      ],
      description: [
        { max: 1500, message: '描述长度不能超过1500个字符', trigger: 'blur' },
      ],
      sort: [
        { required: true, message: '请输入排序', trigger: 'blur' },
      ],
    };
    
    const columns = [
      {
        title: '序号',
        key: 'index',
        width: 80,
        customRender: ({ index }) => index + 1
      },
      {
        title: '活动图片',
        dataIndex: 'imageUrl',
        key: 'image',
        width: 150,
      },
      {
        title: '推荐标题',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '活动名称',
        dataIndex: 'activityName',
        key: 'activityName',
      },
      {
        title: '预告展示时间',
        key: 'time',
        width: 300,
      },
      {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        width: 80,
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
      },
    ];

    // 获取活动预告列表
    const fetchData = async () => {
      loading.value = true;
      try {
        const response = await axios.get('/api/upcoming/page', {
          params: {
            current: currentPage.value,
            size: pageSize.value,
            title: searchForm.title || undefined,
            status: searchForm.status,
          },
        });
        if (response.data.code === 200) {
          tableData.value = response.data.data.records;
          total.value = response.data.data.total;
        } else {
          message.error(response.data.message || '获取活动预告列表失败');
        }
      } catch (error) {
        console.error('获取活动预告列表出错:', error);
        message.error('获取活动预告列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 表格分页、排序、筛选变化时触发
    const handleTableChange = (pagination) => {
      currentPage.value = pagination.current;
      pageSize.value = pagination.pageSize;
      fetchData();
    };

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1;
      fetchData();
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.title = '';
      searchForm.status = undefined;
      currentPage.value = 1;
      fetchData();
    };

    // 新增活动预告
    const handleAdd = () => {
      isEdit.value = false;
      dialogTitle.value = '新增活动预告';
      resetForm();
      dialogVisible.value = true;
    };

    // 编辑活动预告
    const handleEdit = (record) => {
      isEdit.value = true;
      dialogTitle.value = '编辑活动预告';
      Object.assign(form, record);
      imageUrl.value = record.imageUrl;
      
      // 设置时间范围
      if (record.startTime && record.endTime) {
        timeRange.value = [
          dayjs(record.startTime),
          dayjs(record.endTime)
        ];
      }
      
      dialogVisible.value = true;
    };

    // 删除活动预告
    const handleDelete = async (id) => {
      try {
        const response = await axios.delete(`/api/upcoming/${id}`);
        if (response.data.code === 200) {
          message.success('删除成功');
          fetchData();
        } else {
          message.error(response.data.message || '删除失败');
        }
      } catch (error) {
        console.error('删除活动预告出错:', error);
        message.error('删除失败');
      }
    };

    // 重置表单
    const resetForm = () => {
      form.id = '';
      form.title = '';
      form.imageUrl = '';
      form.startTime = '';
      form.endTime = '';
      form.activityId = undefined;
      form.description = '';
      form.sort = 0;
      form.status = 0;
      imageUrl.value = '';
      fileList.value = [];
      timeRange.value = [];
    };

    // 取消弹窗
    const handleModalCancel = () => {
      dialogVisible.value = false;
      resetForm();
    };

    // 提交表单
    const submitForm = () => {
      formRef.value.validate().then(async () => {
        modalLoading.value = true;
        try {
          let response;
          if (isEdit.value) {
            response = await axios.put(`/api/upcoming/${form.id}`, form);
          } else {
            response = await axios.post('/api/upcoming', form);
          }
          
          if (response.data.code === 200) {
            message.success(isEdit.value ? '更新成功' : '添加成功');
            dialogVisible.value = false;
            resetForm();
            fetchData();
          } else {
            message.error(response.data.message || (isEdit.value ? '更新失败' : '添加失败'));
          }
        } catch (error) {
          console.error(isEdit.value ? '更新活动预告出错:' : '添加活动预告出错:', error);
          message.error(isEdit.value ? '更新失败' : '添加失败');
        } finally {
          modalLoading.value = false;
        }
      }).catch(error => {
        console.log('表单验证失败:', error);
      });
    };
    
    // 打开活动选择器
    const openActivitySelector = () => {
      activitySelectorVisible.value = true;
      activitySearchKeyword.value = '';
      activityPagination.current = 1;
      fetchActivityList();
    };

    // 关闭活动选择器
    const handleActivitySelectorCancel = () => {
      activitySelectorVisible.value = false;
    };

    // 获取活动列表
    const fetchActivityList = (page = activityPagination.current, pageSize = activityPagination.pageSize) => {
      activityLoading.value = true;
      const params = {
        current: page,
        size: pageSize,
        name: activitySearchKeyword.value || undefined,
      };
      
      axios.get('/api/activity/page', { params })
        .then(response => {
          if (response.data.code === 200) {
            activityList.value = response.data.data.records;
            activityPagination.total = response.data.data.total;
            activityPagination.current = page;
          } else {
            message.error(response.data.message || '获取活动列表失败');
          }
        })
        .catch(error => {
          console.error('获取活动列表失败:', error);
          message.error('获取活动列表失败');
        })
        .finally(() => {
          activityLoading.value = false;
        });
    };

    // 搜索活动
    const searchActivities = () => {
      activityPagination.current = 1;
      fetchActivityList();
    };

    // 活动表格分页变化
    const handleActivityTableChange = (pagination) => {
      fetchActivityList(pagination.current, pagination.pageSize);
    };

    // 选择活动
    const selectActivity = (record) => {
      form.activityId = record.id;
      activitySelectorVisible.value = false;
      message.success(`已选择活动：${record.name}`);
    };

    // 上传前校验
    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('只能上传JPG或PNG格式的图片!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过2MB!');
      }
      return isJpgOrPng && isLt2M;
    };

    // 处理上传变化
    const handleChange = (info) => {
      if (info.file.status === 'uploading') {
        imageLoading.value = true;
        return;
      }
      if (info.file.status === 'done') {
        imageLoading.value = false;
        if (info.file.response.code === 200) {
          imageUrl.value = info.file.response.data;
          form.imageUrl = info.file.response.data;
        } else {
          message.error(info.file.response.message || '上传失败');
        }
      } else if (info.file.status === 'error') {
        imageLoading.value = false;
        message.error('上传失败');
      }
    };




    onMounted(() => {
      fetchData();
    });

    return {
      formRef,
      loading,
      tableData,
      total,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      isEdit,
      modalLoading,
      imageUrl,
      imageLoading,
      fileList,
      timeRange,
      searchForm,
      form,
      rules,
      columns,
      handleTableChange,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleModalCancel,
      submitForm,
      beforeUpload,
      handleChange,
      // 活动选择器相关
      activitySelectorVisible,
      activityList,
      activityLoading,
      activitySearchKeyword,
      activityPagination,
      activityColumns,
      openActivitySelector,
      handleActivitySelectorCancel,
      searchActivities,
      handleActivityTableChange,
      selectActivity,
    };
  },
});
</script>

<style scoped>
.upcoming-list {
  background-color: transparent;
}
.search-card {
  margin-bottom: 20px;
}
.avatar-uploader {
  /* display: flex; */
}
.ant-upload-text {
  margin-top: 8px;
}
.activity-selector {
  padding: 0 10px;
}
.search-bar {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 16px;
}
</style>